package com.book.servlet.auth;

import com.book.service.UserService;
import com.book.service.impl.UserServiceImpl;
import com.book.utils.ThymeleafUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService service;

    @Override
    // 初始化登录逻辑接口
    public void init() throws ServletException {
        service = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Context context = new Context();
        // 验证登录是否成功
        if (req.getSession().getAttribute("Login-failure") != null) {
            // 登录不成功则向前端发送一个ture，使前端显示红色提示。
            context.setVariable("failure", true);
            req.getSession().removeAttribute("Login-failure");
        }
        if(req.getSession().getAttribute("user") != null){
            resp.sendRedirect("index");
        }
        ThymeleafUtils.process("login.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //首先设置一下响应类型
        resp.setContentType("text/html;charset=UTF-8");
        //获取POST请求携带的表单数据
        Map<String, String[]> map = req.getParameterMap();
        //判断表单是否完整
        if (map.containsKey("username") && map.containsKey("password")) {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            // 验证登录
            if (service.auth(username, password, req.getSession())) {
                resp.sendRedirect("index");
            } else {
                // 如果登录失败，应在session里添加一个标记，使前端显示红色提示。
                req.getSession().setAttribute("Login-failure", new Object());
                this.doGet(req, resp);
            }

        } else {
            resp.getWriter().write("错误，您的表单数据不完整！");
        }
    }
}
